package com.niit.mobileDevide.appusagetime;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class AppUsageTimeMapper extends Mapper<LongWritable, Text, Text, Text> {

    private static final int GENDER_INDEX = 9; // 性别
    private static final int APP_USAGE_TIME_INDEX = 3; // 应用程序使用时间

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length <= Math.max(GENDER_INDEX, APP_USAGE_TIME_INDEX)) { // 确保有足够的字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 使用性别作为key的一部分，并将其映射为"Male"或"Female"
            String genderCode = columns[GENDER_INDEX].trim();
            String gender;
            if ("1".equals(genderCode)) {
                gender = "Male";
            } else if ("2".equals(genderCode)) {
                gender = "Female";
            } else {
                System.err.println("Invalid gender code: " + genderCode + ". Skipping line.");
                return;
            }

            // 获取应用程序使用时间并去除前后空白
            String appUsageTimeStr = columns[APP_USAGE_TIME_INDEX].trim();
            double appUsageTime = Double.parseDouble(appUsageTimeStr);

            // 输出性别和应用程序使用时间
            context.write(new Text(gender), new Text(String.valueOf(appUsageTime)));

        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}